package com.example.shirodemo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;



/**
 * ShiroTest   com.example.shirodemo.controller
 *
 * @author：黄玉刚 -成都电安惠科有限公司
 * @date： 2019/11/30 20:39
 * @Description ：
 */
@RestController
public class LoginController {

    @PostMapping("/doLogin")
    public String doLogin(String username,String password){
        Subject subject= SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username, password));
            subject.getSession().setAttribute(subject.getSession().getId(),username);
        }catch (AuthenticationException e){
            e.printStackTrace();
            System.out.println("登录失败！");
            return "登录失败！";
        }
        return "redirct:/hello";
    }
    @GetMapping("/hello")
    public String hello() {
        return "你能顺利访问该数据：hello";
    }
    @GetMapping("/login")
    public String  login() {
        return "please login(请登录)!";
    }

    @GetMapping("/user")
    @RequiresRoles({"user"})
    public String  user() {
        return "能顺利访问/user";
    }

    @GetMapping("/admin")
    @RequiresRoles({"admin"})
    public String  admin() {
        return "能顺利访问/admin";
    }

    @GetMapping("/unauthorerror")
    public String  unauthorerror() {
        return "对不起，您没有该权限！";
    }



}
